package body

import (
	"errors"
	"fmt"
	"strings"
	"udp_tcp_client/util"
)

type BodyItem struct {
	keys   []string
	values []string
}

func (b *BodyItem) NewBoadyItem(s string) error {
	stringSlice := strings.Split(s, util.LF)
	err := b.NewBodyStringArray(stringSlice, 0)
	if err != nil {
		return err
	}
	return nil
}

func (b *BodyItem) GetFirstItemValue(s string) (error, string) {
	for i, value := range b.keys {
		if value == s {
			return nil, b.values[i]
		}
	}
	return errors.New("找不到该值"), ""
}

func (b *BodyItem) NewBodyStringArray(s []string, i int) error {
	for ; i < len(s); i++ {
		ss := s[i]
		ss = strings.Replace(ss, util.LF, "", -1)
		ss = strings.Replace(ss, util.CR, "", -1)
		if 0 == len(ss) {
			continue
		}
		b.keys = append(b.keys, ss[0:1])
		b.values = append(b.values, ss[2:])
	}
	return nil
}

func (b *BodyItem) String() string {
	builder := strings.Builder{}
	for i := 0; i < len(b.keys); i++ {
		builder.WriteString(fmt.Sprintf("%s=%s"+util.CRLF, b.keys[i], b.values[i]))
	}
	return builder.String()
}
